package com.ingenio.siot.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ingenio.siot.adapter.PermisoAdapter;
import com.ingenio.siot.adapter.RolAdapter;
import com.ingenio.siot.entity.Permiso;
import com.ingenio.siot.entity.Rol;

/**
 * Servlet implementation class DevolverCalleServlet
 */
@WebServlet("/AsignarPermisos")
public class AsignarPermisosServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AsignarPermisosServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(request.getParameter("text") != ""){
			String jsonRoles = request.getParameter("text");
			PermisoAdapter pa = new PermisoAdapter();
			RolAdapter ra = new RolAdapter();
			try {
				JSONArray jroles = new JSONArray(jsonRoles);
				List<Rol> roles = new ArrayList<Rol>();
				Rol r = null;
				for(int i=0;i<jroles.length();i++){
					JSONObject jo = (JSONObject) jroles.get(i);
					Integer idRol = jo.getInt("idRol");
					JSONArray arrayPermisos = jo.getJSONArray("permisos");
					r = new Rol(idRol, null, true);
					List<Permiso> permisosRol = new ArrayList<Permiso>();
					for(int j=0;j<arrayPermisos.length();j++){
						Integer idPermiso = Integer.parseInt(arrayPermisos.getString(j));
						permisosRol.add(pa.devolverPermiso(idPermiso));
					}
					r.setPermisosRol(permisosRol);
					roles.add(r);
				}
				ra.crearRolesPermisos(roles);
				JSONObject jo = new JSONObject();
				try {
					jo.put("error", false);
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
				response.setContentType("application/json");
				response.getWriter().write(jo.toString());
			}
			catch (Exception e) {
				e.printStackTrace();
				JSONObject jo = new JSONObject();
				try {
					jo.put("error", false);
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
				response.setContentType("application/json");
				response.getWriter().write(jo.toString());
			}
		}
	}

}
